package dwl.graduation.design.service.impl;

import dwl.graduation.design.domain.Permission;
import dwl.graduation.design.domain.PermissionExample;
import dwl.graduation.design.domain.PermissionInsertRequest;
import dwl.graduation.design.domain.PermissionUpdateRequest;
import dwl.graduation.design.mapper.PermissionMapper;
import dwl.graduation.design.service.PermissionService;
import dwl.graduation.design.utils.PageResult;
import dwl.graduation.design.utils.QueryPageBean;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

@Service
public class PermissionServiceImpl implements PermissionService {

    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public PageResult findPermissionList(QueryPageBean queryPageBean) {
        if (!Objects.isNull(queryPageBean.getPageSize()) && !Objects.isNull(queryPageBean.getCurrentPage())) {
            queryPageBean.setCurrentPage((queryPageBean.getCurrentPage() - 1) * queryPageBean.getPageSize());
        }
        List<Permission> permissionList = permissionMapper.getPermissionList(queryPageBean);
        Long count = permissionMapper.getListCount(queryPageBean);
        return PageResult.builder().rows(permissionList).total(count).build();
    }

    @Override
    public boolean insertPermission(PermissionInsertRequest request) {
        Permission permission = new Permission();
        BeanUtils.copyProperties(request, permission);
        int flag = permissionMapper.insertSelective(permission);
        return flag > 0;
    }

    @Override
    public void deletePermission(Integer id) {
        permissionMapper.deleteByPrimaryKey(id);
    }

    @Override
    public boolean updatePermission(PermissionUpdateRequest permissionUpdateRequest) {
        PermissionExample permissionExample = new PermissionExample();
        permissionExample.createCriteria().andIdEqualTo(permissionUpdateRequest.getId());
        List<Permission> permissionList = permissionMapper.selectByExample(permissionExample);
        if (permissionList.size() == 0){
            return false;
        }
        Permission permission = new Permission();
        BeanUtils.copyProperties(permissionUpdateRequest, permission);
        PermissionExample permissionUpdateExample = new PermissionExample();
        permissionExample.createCriteria().andIdEqualTo(permission.getId());
        int flag = permissionMapper.updateByExampleSelective(permission, permissionUpdateExample);
        return flag >0;
    }

    @Override
    public Permission findPermissionById(Integer id) {
        return permissionMapper.findPermissionById(id);
    }
}
